package menu

import (
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/user"
	"sg-backend/utils"
)

// MenusJson 树形菜单数据结构
type MenusJson struct {
	Id            uint        `json:"id"`
	Pid           uint        `json:"pid"`
	Title         string      `json:"title"`
	Icon          string      `json:"icon"`
	Url           string      `json:"url"`
	OrderNum      uint        `json:"orderNum"`
	PrivilegeName string      `json:"privilegeName"`
	Show          bool        `json:"show"`
	Value         uint        `json:"value"`
	Key           uint        `json:"key"`
	Children      []MenusJson `json:"children"`
}

/*
 * method  GET
 * path    /api/user/menu
 */

// GetMenu GET请求，获取菜单Tree结构数据
func GetMenu(ctx *fiber.Ctx) error {

	// 获取并处理
	treeData := GetMenuTree(0)
	return ctx.JSON(fiber.Map{
		"success": true,
		"status":  "done",
		"message": "请求成功！",
		"data":    treeData,
	})
}

/*
 * 1
 * GET /api/user/menu
 * GetMenuTree 获取菜单数据，treeTable结构
 */

func GetMenuTree(deptPid uint) []MenusJson {

	// 权限验证
	utils.CheckPermsByTag("UserMenu", global.AuthUser.UserId, "read")

	// 根据Pid，获取部门信息
	var menuList []user.Menu
	global.DB.Order("order_num").Where("pid = ?", deptPid).Find(&menuList)

	// 整理数据
	var data []MenusJson

	for _, v := range menuList {

		// 验证是否有权限
		hasPerm := utils.CheckPermsByTag(v.PrivilegeName, global.AuthUser.UserId, "read")
		if hasPerm == true {

			// 用户有权限
			// 递归获取children
			subData := GetMenuTree(v.Id)
			if len(subData) != 0 {

				// 有下层菜单
				data = append(data, MenusJson{
					Id: v.Id, Title: v.Title, Icon: v.Icon, Url: v.Url, OrderNum: v.OrderNum, Pid: v.Pid,
					PrivilegeName: v.PrivilegeName, Show: v.Show, Value: v.Id, Key: v.Id, Children: subData,
				})
			} else {

				// 无下层菜单
				data = append(data, MenusJson{
					Id: v.Id, Title: v.Title, Icon: v.Icon, Url: v.Url, OrderNum: v.OrderNum, Pid: v.Pid,
					PrivilegeName: v.PrivilegeName, Show: v.Show, Value: v.Id, Key: v.Id,
				})
			}

		}
	}

	return data
}
